<template>
  <div class="wheel-container">
    <!-- 标题区域，包含输入框和历史按钮 -->
    <div class="title-section">
      <div
        ref="titleEditable"
        contenteditable
        class="theme-input"
        :class="{ 'theme-placeholder': showPlaceholder }"
        @focus="handleTitleFocus"
        @blur="handleTitleBlur"
        @input="updateTitle"
        @keydown.enter.prevent="blurTitle"
      ></div>
      <button @click="toggleHistory" class="history-button">
        {{ showHistory ? "隐藏历史" : "查看历史" }}
      </button>
    </div>

    <!-- 历史记录区域，支持滑动 -->
    <div v-if="showHistory" class="history-section">
      <ul class="history-list">
        <li
          v-for="(history, index) in historyList"
          :key="index"
          class="history-item"
          @click="loadHistory(index)"
        >
          {{ history.title || '未命名轮盘' }} - {{ history.date }}
        </li>
      </ul>
    </div>

    <!-- 选项管理 -->
    <div class="options-section">
      <div class="option-input-container">
        <input
          v-model="newOption"
          type="text"
          placeholder="添加新选项"
          class="option-input"
          @keyup.enter="addOption"
        />
        <button @click="addOption" class="add-button">添加</button>
      </div>
      <ul class="option-list">
        <li v-for="(option, index) in options" :key="index" class="option-item">
          <input v-model="option.text" type="text" class="option-text" />
          <input
            v-model.number="option.weight"
            type="number"
            min="1"
            max="10"
            class="option-weight"
            placeholder="权重"
          />
          <button @click="removeOption(index)" class="delete-button">删除</button>
        </li>
      </ul>
    </div>

    <!-- 旋转时间 -->
    <div class="duration-control">
      <span class="duration-label">旋转时间（秒）:</span>
      <input
        v-model.number="spinDuration"
        type="number"
        min="1"
        max="5"
        step="0.5"
        class="duration-input"
      />
    </div>

    <!-- 转盘可视化 -->
    <div class="wheel-wrapper">
      <canvas ref="canvas" width="400" height="400" class="wheel-canvas"></canvas>
    </div>

    <!-- 控制按钮和结果 -->
    <div class="controls-section">
      <button
        @click="spin"
        :disabled="spinning || options.length < 2"
        class="spin-button"
      >
        {{ spinning ? "转动中..." : "开始转动" }}
      </button>
      <div class="result-container">
        <transition name="fade">
          <p v-if="result" class="result">🎉 {{ result }} 🎉</p>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';

// 标题相关状态
const title = ref('');
const showPlaceholder = ref(true);
const titleEditable = ref(null);

// 选项相关状态
const newOption = ref('');
const options = ref([
  { text: '选项1', weight: 1 },
  { text: '选项2', weight: 1 },
]);

// 转盘控制状态
const spinDuration = ref(2);
const spinning = ref(false);
const result = ref('');

// 历史记录状态
const showHistory = ref(false);
const historyList = ref(JSON.parse(localStorage.getItem('wheelHistory')) || []);

// 画布相关
const canvas = ref(null);
const ctx = ref(null);
let rotation = 0;
const pointerAngleDeg = 270;
let highlightedIndex = -1;

// 转盘颜色
const segmentColors = [
  '#4ade80', '#60a5fa', '#f472b6', '#facc15', '#a78bfa', '#fb923c'
];

// 处理标题聚焦，清除占位符
function handleTitleFocus() {
  if (showPlaceholder.value) {
    showPlaceholder.value = false;
    nextTick(() => {
      titleEditable.value.innerText = '';
      focusEndOfContent(titleEditable.value);
    });
  }
}

// 处理标题失焦，恢复占位符
function handleTitleBlur() {
  if (!title.value.trim()) {
    showPlaceholder.value = true;
    titleEditable.value.innerText = '';
  }
}

// 处理全局点击，恢复占位符
function handleGlobalClick(event) {
  if (titleEditable.value && !titleEditable.value.contains(event.target)) {
    if (!title.value.trim()) {
      showPlaceholder.value = true;
      titleEditable.value.innerText = '';
    }
  }
}

// 更新标题内容
function updateTitle() {
  title.value = titleEditable.value.innerText.trim();
}

// 回车键失焦标题输入框
function blurTitle() {
  titleEditable.value.blur();
}

// 光标定位到内容末尾
function focusEndOfContent(element) {
  const range = document.createRange();
  const selection = window.getSelection();
  range.selectNodeContents(element);
  range.collapse(false);
  selection.removeAllRanges();
  selection.addRange(range);
}

// 保存轮盘到历史记录（倒序）
function saveHistory() {
  const historyItem = {
    title: title.value || '未命名轮盘',
    options: [...options.value],
    date: new Date().toLocaleString('zh-CN'),
  };
  historyList.value.unshift(historyItem); // 插入到数组开头
  localStorage.setItem('wheelHistory', JSON.stringify(historyList.value));
}

// 加载历史轮盘
function loadHistory(index) {
  const history = historyList.value[index];
  title.value = history.title;
  options.value = [...history.options];
  titleEditable.value.innerText = history.title;
  showPlaceholder.value = !history.title;
  showHistory.value = false;
}

// 切换历史记录显示状态
function toggleHistory() {
  showHistory.value = !showHistory.value;
}

// 计算选项总权重
function totalWeight() {
  return options.value.reduce((sum, opt) => sum + (opt.weight || 1), 0);
}

// 截断过长文本以适应显示
function truncateText(text, maxWidth, ctx) {
  let truncated = text;
  while (ctx.measureText(truncated).width > maxWidth && truncated.length > 0) {
    truncated = truncated.slice(0, -1);
  }
  return truncated.length < text.length ? truncated + '...' : truncated;
}

// 绘制转盘
function drawWheel() {
  const c = ctx.value;
  const cvs = canvas.value;
  const center = cvs.width / 2; // 中心点为 200
  const radius = center - 15; // 半径为 185

  c.clearRect(0, 0, cvs.width, cvs.height);

  const total = totalWeight();
  let startAngle = rotation;

  options.value.forEach((opt, i) => {
    const angle = (opt.weight / total) * 2 * Math.PI;
    c.beginPath();
    c.moveTo(center, center);
    c.arc(center, center, radius, startAngle, startAngle + angle);
    c.closePath();
    c.fillStyle = segmentColors[i % segmentColors.length];
    c.fill();
    c.strokeStyle = '#e5e7eb';
    c.lineWidth = 2;
    c.stroke();

    // 绘制选项文字
    c.save();
    c.translate(center, center);
    c.rotate(startAngle + angle / 2);
    c.textAlign = 'right';
    c.fillStyle = '#1f2937';
    c.font = 'bold 20px Arial';
    const maxTextWidth = radius - 20;
    const truncatedText = truncateText(opt.text, maxTextWidth, c);
    c.fillText(truncatedText, radius - 15, 0);
    c.restore();

    startAngle += angle;
  });

  // 绘制指针（紫色）
  c.beginPath();
  c.moveTo(center - 20, center - radius - 15);
  c.lineTo(center + 20, center - radius - 15);
  c.lineTo(center, center - radius + 15);
  c.closePath();
  c.fillStyle = '#a78bfa'; // 紫色指针
  c.fill();
  c.strokeStyle = '#e5e7eb';
  c.lineWidth = 2;
  c.stroke();
}

// 缓动函数，平滑旋转效果
function easeOutQuart(t) {
  return 1 - Math.pow(1 - t, 4);
}

// 旋转转盘
function spin() {
  if (options.value.length < 2) return;

  // 保存当前轮盘到历史记录
  saveHistory();

  spinning.value = true;
  result.value = '';
  highlightedIndex = -1;

  // 滚动到页面底部
  window.scrollTo({
    top: document.body.scrollHeight,
    behavior: 'smooth'
  });

  const spins = 5 + Math.floor(Math.random() * 3);
  const finalRotationDeg = spins * 360 + Math.random() * 360;
  const finalRotationRad = (finalRotationDeg * Math.PI) / 180;

  const duration = spinDuration.value * 1000;
  let start = null;

  function animate(ts) {
    if (!start) start = ts;
    const elapsed = ts - start;
    const progress = Math.min(elapsed / duration, 1);
    const eased = easeOutQuart(progress);

    rotation = eased * finalRotationRad;
    drawWheel();

    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      const rotationDeg = ((rotation * 180) / Math.PI) % 360;
      const pointer = (360 - rotationDeg + pointerAngleDeg) % 360;

      const total = totalWeight();
      let acc = 0;
      for (let i = 0; i < options.value.length; i++) {
        const segAngle = (options.value[i].weight / total) * 360;
        if (pointer >= acc && pointer < acc + segAngle) {
          highlightedIndex = i;
          break;
        }
        acc += segAngle;
      }

      drawWheel();
      result.value = options.value[highlightedIndex].text;
      spinning.value = false;
    }
  }

  requestAnimationFrame(animate);
}

// 添加新选项
function addOption() {
  if (newOption.value.trim()) {
    options.value.push({ text: newOption.value.trim(), weight: 1 });
    newOption.value = '';
  }
}

// 删除选项
function removeOption(index) {
  if (options.value.length > 2) {
    options.value.splice(index, 1);
  } else {
    alert('至少保留两个选项！');
  }
}

// 初始化画布和全局点击监听
onMounted(() => {
  ctx.value = canvas.value.getContext('2d');
  drawWheel();
  document.addEventListener('click', handleGlobalClick);
});

// 清理全局点击监听
onBeforeUnmount(() => {
  document.removeEventListener('click', handleGlobalClick);
});

// 监听选项变化，重新绘制
watch(
  options,
  () => {
    highlightedIndex = -1;
    drawWheel();
  },
  { deep: true }
);
</script>

<style scoped>
/* 整体容器，白色背景 */
.wheel-container {
  max-width: 700px;
  margin: 30px auto;
  padding: 24px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  text-align: center;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e7ff;
}

/* 标题区域，水平排列输入框和按钮 */
.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

/* 标题输入框 */
.theme-input {
  font-size: 26px;
  font-weight: 600;
  padding: 12px;
  border: 2px solid transparent;
  border-radius: 8px;
  background: #ffffff;
  color: #1f2937; /* 深色文字 */
  flex: 1;
  text-align: center;
  outline: none;
  transition: border-color 0.3s ease;
}
.theme-input:focus {
  border-color: #a78bfa; /* 紫色边框 */
  box-shadow: 0 0 8px rgba(167, 139, 250, 0.3);
}
.theme-placeholder {
  color: #9ca3af;
}
.theme-placeholder:empty::before {
  content: '点击此处可输入主题';
  color: #9ca3af;
  font-style: italic;
}

/* 历史按钮 */
.history-button {
  padding: 10px 20px;
  background: linear-gradient(135deg, #a78bfa, #8b5cf6); /* 紫色渐变 */
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background 0.3s ease, transform 0.2s ease;
}
.history-button:hover {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
  transform: translateY(-2px);
}

/* 历史记录区域，支持滑动 */
.history-section {
  max-height: 200px; /* 固定高度，超出滚动 */
  overflow-y: auto; /* 启用垂直滚动条 */
  margin-bottom: 16px;
  padding: 12px;
  background: #ffffff; /* 白色背景 */
  border-radius: 8px;
  border: 1px solid #e0e7ff;
}
.history-section::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}
.history-section::-webkit-scrollbar-thumb {
  background: #a78bfa; /* 紫色滚动条 */
  border-radius: 4px;
}
.history-section::-webkit-scrollbar-track {
  background: #f3f4f6; /* 浅灰色轨道 */
}
.history-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.history-item {
  padding: 10px;
  border-bottom: 1px solid #e0e7ff;
  cursor: pointer;
  color: #1f2937; /* 深色文字 */
  transition: background 0.2s ease;
  font-size: 14px;
}
.history-item:hover {
  background: #f3e8ff; /* 浅紫色悬停 */
}
.history-item:last-child {
  border-bottom: none;
}

/* 选项区域 */
.options-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #ffffff;
  border-radius: 10px;
  border: 1px solid #e0e7ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.option-input-container {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}
.option-input {
  flex: 1;
  padding: 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  outline: none;
  background: #f9fafb;
  transition: border-color 0.3s ease;
}
.option-input:focus {
  border-color: #a78bfa; /* 紫色边框 */
}
.add-button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #a78bfa, #8b5cf6);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s ease;
}
.add-button:hover {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}
.option-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.option-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e0e7ff;
  transition: background 0.2s ease;
}
.option-item:hover {
  background: #f3e8ff; /* 浅紫色悬停 */
}
.option-item:last-child {
  border-bottom: none;
}
.option-text,
.option-weight {
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  outline: none;
  background: #f9fafb;
}
.option-text:focus,
.option-weight:focus {
  border-color: #a78bfa;
}
.option-weight {
  width: 80px;
}
.delete-button {
  padding: 10px 20px;
  background: linear-gradient(135deg, #a78bfa, #8b5cf6);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.3s ease;
}
.delete-button:hover {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}

/* 旋转时间控制 */
.duration-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 24px;
  padding: 12px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #e0e7ff;
}
.duration-label {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
}
.duration-input {
  width: 80px;
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  outline: none;
  background: #f9fafb;
}
.duration-input:focus {
  border-color: #a78bfa;
}

/* 转盘区域 */
.wheel-wrapper {
  margin: 24px auto;
  width: 420px;
  height: 420px;
  background: #ffffff;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}
.wheel-canvas {
  display: block;
  margin: 0 auto;
  border-radius: 50%;
  border: 1px solid #e0e7ff;
}

/* 控制按钮和结果 */
.controls-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}
.spin-button {
  padding: 12px 28px;
  background: linear-gradient(135deg, #a78bfa, #8b5cf6);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: background 0.3s ease, transform 0.2s ease;
}
.spin-button:hover {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
  transform: translateY(-2px);
}
.spin-button:disabled {
  background: #d1d5db;
  cursor: not-allowed;
  transform: none;
}

/* 结果展示 */
.result {
  font-size: 22px;
  font-weight: 600;
  color: #1f2937;
  padding: 12px 24px;
  background: #f3e8ff; /* 浅紫色背景 */
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease, transform 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .wheel-container {
    margin: 15px;
    padding: 16px;
  }
  .theme-input {
    font-size: 22px;
  }
  .history-button {
    padding: 8px 16px;
    font-size: 13px;
  }
  .history-section {
    max-height: 150px; /* 移动端高度更小 */
  }
  .wheel-wrapper {
    width: 360px;
    height: 360px;
  }
  .wheel-canvas {
    width: 340px;
    height: 340px;
  }
  .option-item {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  .spin-button {
    width: 100%;
    padding: 12px;
  }
}
</style>